﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Resources;
using System.Reflection;
using System.IO;
using Ibms.Net.TcpCSFramework;
using BOMSWinService.DATA;

namespace BOMSWinService
{
    public partial class SettingDlg : Form
    {
        private Desktop m_Desktop = new Desktop();
        private IContainer m_Container = null;
        private NotifyIcon m_NotifyIcon = null;
        private Button btnHide;
        private ContextMenu m_ContextMenu = null;
        TcpCli oneCli = null;
        /// <summary>
        /// Start the UI thread
        /// </summary>
        public static SettingDlg StartUIThread()
        {
            SettingDlg dlg = new SettingDlg();
            dlg.Visible = false;
            Thread thread = new Thread(new ThreadStart(dlg.UIThread));
            thread.Start();

            return dlg;
        }

        /// <summary>
        /// UI thread
        /// </summary>
        public void UIThread()
        {
            if( !m_Desktop.BeginInteraction() )
                return;
            //this.Visible = false;
            Application.Run(this);
        }

        protected SettingDlg()
        {
            InitializeComponent();
        }  
        /// <summary>
        /// Move the window to the right-bottom corner
        /// </summary>
        /// <param name="e"></param>
        protected override void OnShown(EventArgs e)
        {
            this.Left = Screen.PrimaryScreen.WorkingArea.Left
                + Screen.PrimaryScreen.WorkingArea.Width
                - this.Width
                ;
            this.Top = Screen.PrimaryScreen.WorkingArea.Top
                + Screen.PrimaryScreen.WorkingArea.Height
                - this.Height
                ;
        }
        private void SettingDlg_Load(object sender, EventArgs e)
        {
            
            #region 原始
            m_ContextMenu = new ContextMenu();
            m_ContextMenu.MenuItems.Add(new MenuItem("Operate", this.OpenDialog));
            m_ContextMenu.MenuItems.Add(new MenuItem("Configuration", this.OpenConfigWindow));
            m_ContextMenu.MenuItems[0].DefaultItem = true;

            Assembly asm = Assembly.GetExecutingAssembly(); //---获取程序集
            Stream sm = asm.GetManifestResourceStream("BOMSWinService.damotouicon.ico");

            Icon icon = new Icon(sm, 16, 16);
            m_Container = new Container();
            
            m_NotifyIcon = new NotifyIcon(m_Container);
            m_NotifyIcon.ContextMenu = m_ContextMenu;
            m_NotifyIcon.Icon = icon;
            m_NotifyIcon.Visible = true;
            m_NotifyIcon.DoubleClick += new EventHandler(this.OpenDialog);

            m_NotifyIcon.ShowBalloonTip( 200
                , "In service"
                , "CET电源监控系统BOMS服务开启了！"
                , ToolTipIcon.Info
                );
            #endregion

            BindEquipToRadios();
            //this.Hide();//隐藏主窗体            
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
        }

        private void BindEquipToRadios()
        {
            DataUti du = new DataUti();
            List<EquipModel> list = du.GetEquipModelList(true);
            for (int i = 0; i < list.Count; i++)
            {
                RadioButton radio = new RadioButton();
                radio.Text = "主机" + list[i].ClientHostIP;
                radio.Tag = list[i].ClientHostIP + ":" + list[i].Port;
                radio.Width = 200;

                radio.Left = 5;
                radio.Top = i * 20 + 20;
                groupBox1.Controls.Add(radio);
                if (i == 0)
                {
                    radio.Checked = true;
                }
            }

        }

        public void OpenDialog(Object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Left = Screen.PrimaryScreen.WorkingArea.Left
               + Screen.PrimaryScreen.WorkingArea.Width
               - this.Width
               ;
            this.Top = Screen.PrimaryScreen.WorkingArea.Top
                + Screen.PrimaryScreen.WorkingArea.Height
                - this.Height;
            this.BringToFront();
        }
        public void OpenConfigWindow(Object sender, EventArgs e)
        {
            //this.Visible = true;
           // BringToFront();
            SettingCfg cfg = new SettingCfg();
            cfg.ShowIcon = false;
            cfg.ShowDialog();
            cfg.Left = Screen.PrimaryScreen.WorkingArea.Left
               + Screen.PrimaryScreen.WorkingArea.Width
               - cfg.Width
               ;
            cfg.Top = Screen.PrimaryScreen.WorkingArea.Top
                + Screen.PrimaryScreen.WorkingArea.Height
                - cfg.Height;
            
           
        }

        protected override void OnClosed(EventArgs e)
        {
            m_NotifyIcon.Dispose();
            m_ContextMenu.Dispose();
            m_Container.Dispose();
        }

        private void btnHide_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {  
        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 收到数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void RecvData(object sender, NetEventArgs e)
        {
            //TcpCli cli = (TcpCli)sender;
            //string rcvData = e.Client.Datagram;
            //string dataToShow = rcvData.Substring(0, rcvData.Length - 2);
            //string xml = BuildData.BuildXmlData(dataToShow);
            //string mac = "00:00:00:00:00:11";
            //string ip = cli.SvrIp;
            //string dtm = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //DataUti.ImportEquipData(ip, mac, dtm, xml);
            // string info = string.Format("recv data:{0} from:{1}.", dataToShow, e.Client);
            //SetTextControl(info, 1, true, this.textBoxFeedBack);
        }

        void oneCli_ReceivedDatagramCus(object sender, byte[] arr)
        {
           // ProtocolPack pack = BuildData.Converting(arr);

        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 客户端连接事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void ClientConn(object sender, NetEventArgs e)
        {
            string info = string.Format("A Client:{0} connect server :{1}", e.Client,
            e.Client.ClientSocket.RemoteEndPoint.ToString());
            //SetTextControl(info, 1, true, this.textBoxFeedBack);
            //SetTextControl("请求连接成功", 0, true, this.labelState);
            //SetControlEnable(this.textBoxSrvIP, false);
            //SetControlEnable(this.textBoxSrvPort, false);
            //SetControlEnable(this.buttonConn, false);
            //SetControlEnable(this.buttonClose, true);
        }
        ///-----------------------------------------------------------------*
        /// <summary>
        /// 客户端关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------*
        void ClientClose(object sender, NetEventArgs e)
        {
            TcpCli cli = (TcpCli)sender;
            string info;

            if (e.Client.TypeOfExit == Session.ExitType.ExceptionExit)
            {
                info = string.Format("A Client Session:{0} Exception Closed.", e.Client.ID);
            }
            else
            {
                info = string.Format("A Client Session:{0} Normal Closed.", e.Client.ID);
            }
            cli.Close();//关闭连接
            //SetTextControl(info, 1, true, this.textBoxFeedBack);
            //SetControlEnable(this.buttonConn, true);
        }

   
        private TcpCli EnsureClient()
        {
            //重新分配Client
            if (oneCli != null)
            {
                oneCli.Close();
                oneCli = null;//释放
            }
           
                string ipport = "";
                RadioButton radio = null;
                for (int i = 0; i < groupBox1.Controls.Count; i++)
                {
                    radio = groupBox1.Controls[i] as RadioButton;
                    if (radio != null && radio.Checked)
                    {
                        ipport = radio.Tag.ToString();
                    }
                }
                if (!string.IsNullOrEmpty(ipport))
                {
                    string[] arr = ipport.Split(':');
                    oneCli = new TcpCli();
                    oneCli.SvrIp = arr[0];
                    oneCli.SvrPort = int.Parse(arr[1]);
                    //添加事件
                    oneCli.Resovlver = new DatagramResolver("##");
                    oneCli.ReceivedDatagram += new NetEvent(this.RecvData);
                    oneCli.DisConnectedServer += new NetEvent(this.ClientClose);
                    oneCli.ConnectedServer += new NetEvent(this.ClientConn);
                    oneCli.ReceivedDatagramCus += new NetEventCus(this.oneCli_ReceivedDatagramCus);
                }
                else
                {
                    throw new Exception("请选择一台现场主机");
                }
          

            int m=0;
            while (!oneCli.IsConnected && m++<10)
            {
                //连接
                oneCli.Connect(oneCli.SvrIp, oneCli.SvrPort);
                Thread.Sleep(500);
            }
            return oneCli;
        }
        private void btnSTTC_Click(object sender, EventArgs e)
        {
            TcpCli oneCli = EnsureClient();
            if (oneCli.IsConnected)
            {
                //发送数据请求
                oneCli.Send("STTC");
            }
            else
            {
                MessageBox.Show("与"+oneCli.SvrIp+"联接失败！");
            }
        }

        private void btnSTP_Click(object sender, EventArgs e)
        {
            TcpCli oneCli = EnsureClient();
            if (oneCli.IsConnected)
            {
                //发送数据请求
                oneCli.Send("STP");
            }
            else
            {
                MessageBox.Show("与" + oneCli.SvrIp + "联接失败！");
            }
        }

        private void btnSTTD_Click(object sender, EventArgs e)
        {
            TcpCli oneCli = EnsureClient();
            if (oneCli.IsConnected)
            {
                //发送数据请求
                oneCli.Send("STTD");
            }
            else
            {
                MessageBox.Show("与" + oneCli.SvrIp + "联接失败！");
            }
        }

        private void SettingDlg_SizeChanged(object sender, EventArgs e)
        {

            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.m_NotifyIcon.Visible = true;

            }   
        }

    }
}
